package com.tjc.filter;

import com.alibaba.nacos.common.utils.StringUtils;
import com.tjc.apiclientsdk.util.SignUtils;
import com.tjc.common.CommonService;
import com.tjc.exception.BusinessException;
import com.tjc.model.ErrorCode;
import com.tjc.model.entity.InterfaceInfo;
import com.tjc.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName aa
 * @Author tjc
 * <p>
 * 这个类就是对所有满足条件的route进行统一的处理，包括：
 * 鉴权
 **/
@Slf4j
@Component
public class ApiGlobalFilters implements GlobalFilter, Ordered {
    @DubboReference
    CommonService commonService;

    private static final String INTERFACE_PREFIX_URL = "http://loaclhost:7530";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取转发的request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 得到request中的请求url和请求类型
        String methodValue = request.getMethodValue();
        String path = request.getPath().value();

        log.info("path is :" + path);
        // 获取传递的各种的参数
        String body = request.getHeaders().getFirst("body");
        String nonce = request.getHeaders().getFirst("nonce");
        String sign = request.getHeaders().getFirst("sign");
        String accessKey = request.getHeaders().getFirst("accessKey");
        String timestamp = request.getHeaders().getFirst("timestamp");

        // 上列任意内容有空白就直接不给访问
        if (StringUtils.isAnyBlank(body, nonce, sign, accessKey, timestamp)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 如果两次访问之间相差两小时就不给访问
        assert timestamp != null;
        if ((System.currentTimeMillis() - Long.parseLong(timestamp)) > 60 * 60 * 2) {
            throw new BusinessException(ErrorCode.TIME_NOT_ALLOWED);
        }

        // 从数据库中得到登录的用户
        User user = commonService.getUser(accessKey);
        // 从数据库中拿到接口id
        InterfaceInfo interfaceInfo = commonService.getInterfaceInfo(path, methodValue);

        // 从数据库中拿到sk
        String secretKey = commonService.getSecretKey(accessKey);
        if (secretKey == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 对签名进行校验
        String checkSign = SignUtils.getSign(secretKey, body);
        if (!checkSign.equals(sign)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }

        // 打印响应信息


        return handleResponse(exchange, chain, user.getId(), interfaceInfo.getId());
    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long userId, long interfaceInfoId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body is:" + body.toString());
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                // 7. 调用成功，接口调用次数 + 1 invokeCount
                                try {
                                    commonService.invokeCount(userId, interfaceInfoId);
                                    byte[] content = new byte[dataBuffer.readableByteCount()];
                                    dataBuffer.read(content);
                                    DataBufferUtils.release(dataBuffer);// 释放掉内存
                                    // 构建日志
                                    StringBuilder sb2 = new StringBuilder(200);
                                    List<Object> rspArgs = new ArrayList<>();
                                    rspArgs.add(originalResponse.getStatusCode());
                                    String data = new String(content, StandardCharsets.UTF_8); // data
                                    sb2.append(data);
                                    // 打印日志
                                    log.info("响应结果：" + data);
                                    return bufferFactory.wrap(content);
                                } catch (Exception e) {
                                    log.info("invokeCount error");
                                }
                                return bufferFactory.wrap("FAIL INVOKED！".getBytes(StandardCharsets.UTF_8));
                            }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

}



